package com.my.study.handler;

import com.my.study.exception.BusinessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: yidujun
 * @create: 2021/05/12 14:34
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @SuppressWarnings({"rawtypes"})
    public Map globalException(HttpServletRequest request, Exception ex) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("code", 500);
        map.put("message", ex.getMessage());
        return map;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    @SuppressWarnings({"rawtypes"})
    public Map BusinessException(HttpServletRequest request, BusinessException ex) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("code", ex.getCode());
        map.put("message", ex.getMessage());
        return map;
    }

}
